package com.ddj.algorithm.quicksort;

import java.util.Random;

public class RandomizedQs {
    private static Random random = new Random();

    public static void main(String[] args) {
        int[] test = new int[] {3,66,23,532,233,79,54,2,67};
        quickSort(test, 0, test.length - 1);
        for (int item : test) {
            System.out.print(item + " ");
        }

    }

    public static void quickSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int pivot = randomizedPartition(arr, left, right);
        quickSort(arr, left, pivot - 1);
        quickSort(arr, pivot + 1, right);

    }

    public static int randomizedPartition(int[] arr, int left, int right) {
        int pivotIndex = left + random.nextInt(right - left + 1);
        // 随机选定的基准元素与最右边的元素交换
        swap(arr, pivotIndex, right);
        return partition(arr, left, right);
    }


    private static int partition(int[] arr, int left, int right) {
        int pivot = arr[right];
        int i = left - 1;
        for (int j = left; j < right; j++) {
            if (arr[j] < pivot) {
                i++;
                swap(arr, i, j);
            }
        }
        swap(arr, i + 1, right);
        return i + 1;
    }


    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
